﻿using Newtonsoft.Json;
using PosClient.Helper;
using PosClient.Interfaces;
using PosClient.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.Design.AxImporter;

namespace PosClient.Service.Actives
{
    public class ActionService
    {
        public Dictionary<Keys, IActionService> actions = new Dictionary<Keys, IActionService>();
        public ActionService()
        {
            var redis = FreeClient.Redis;
            {
                List<Keyboard> keyList = new List<Keyboard>();
                var keys = redis.HKeys(RedisKey.Redis_Keyboard);
                foreach (var key in keys)
                {
                    var json = redis.HGet(RedisKey.Redis_Keyboard,key);
                    var keyboard = JsonConvert.DeserializeObject<Keyboard>(json);
                    if (keyboard.FormName == "MainView")
                    {
                        keyList.Add(keyboard);
                    }
                }
                SetAction(keyList);

            }
        }

        public IActionService GetAction(Keys key)
        {
            if (!actions.ContainsKey(key)) return null;
            return actions[key];
        }

        public void AddAction(Keyboard keyboard)
        {
            if (keyboard == null) return;
            var redis = FreeClient.Redis;
            if (redis.HExists(RedisKey.Redis_Keyboard, keyboard.ActionName))
            {
                var reflection = ToolService.ReflectionProGrom<IActionService>($"Service.Actives.{keyboard.Command}");
                actions.Add((Keys)keyboard.KeyCode, reflection);
            }
        }

        public void SetAction(List<Keyboard> keyboardList)
        {
            actions.Clear();
            if (keyboardList.Count > 0)
            {
                keyboardList = keyboardList.GroupBy(y => y.KeyCode).Select(x => x.FirstOrDefault()).ToList();
                foreach (var keyboard in keyboardList)
                {
                    var reflection = ToolService.ReflectionProGrom<IActionService>($"Service.Actives.{keyboard.Command}");
                    actions.Add((Keys)keyboard.KeyCode, reflection);
                }
            }
        }
    }
}
